package com.easy.lab.shixun.controller;

import com.easy.lab.shixun.api.bo.request.LoginRequest;
import com.easy.lab.shixun.api.bo.response.TokenInfoResponse;
import com.easy.lab.shixun.api.service.LoginService;
import com.easy.lab.shixun.common.base.BaseError;
import com.easy.lab.shixun.common.base.BaseResponse;
import com.easy.lab.shixun.common.constant.RequestConstant;
import com.easy.lab.shixun.common.utils.RequestUtil;
import com.easy.lab.shixun.service.manager.SimpleCoreManager;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 * @Author: https://gitee.com/wesleyOne
 * @Date: 12.08 2019
 */
@Api(tags = "登录登出相关接口")
@RestController
public class LoginController {

    @Autowired
    private LoginService loginService;

    @Autowired
    private SimpleCoreManager simpleCoreManager;

    @ApiOperation("登录接口")
    @ResponseBody
    @RequestMapping(value = "/login", method = { RequestMethod.POST })
    public BaseResponse<TokenInfoResponse> login(@RequestBody LoginRequest loginParam, HttpServletRequest request, HttpServletResponse response) {
        // 会话已存在
        String token = RequestUtil.getCookievalue(request);
        loginParam.setToken(token);
        // 尝试登录
        TokenInfoResponse tokenInfoResponse = loginService.login(loginParam);
        if (Objects.nonNull(tokenInfoResponse) && tokenInfoResponse.getIsLogin()
                && StringUtils.isNotBlank(tokenInfoResponse.getToken())) {
            RequestUtil.setCookieValue(RequestConstant.TOKEN, tokenInfoResponse.getToken(), response);
            return BaseResponse.success(tokenInfoResponse);
        }
        // 登录失败
        return BaseResponse.error(BaseError.LOGIN_ERROR);
    }

    @ApiOperation("退出接口")
    @ResponseBody
    @RequestMapping(value = "/logout", method = RequestMethod.POST)
    public BaseResponse logout( HttpServletRequest request, HttpServletResponse response) {
        String token = RequestUtil.getCookievalue(request);
        if ( StringUtils.isNotBlank(token)) {
            LoginRequest loginParam = new LoginRequest();
            loginParam.setToken(token);
            loginService.logout(loginParam);
        }
        RequestUtil.clearCookie(RequestConstant.TOKEN, response);
        return BaseResponse.OK;
    }
}
